import numpy as np
from datetime import datetime
from typing import Dict, List
from ..proto import strategy_service_pb2 as pb2

class EventProcessor:
    def __init__(self):
        self.event_queue = []
        self.current_time = None
        
    def process_tick(self, tick: pb2.Tick):
        """处理市场行情事件"""
        self.current_time = tick.timestamp
        # 生成市场事件
        market_event = {
            'type': 'MARKET',
            'symbol': tick.symbol,
            'price': tick.price,
            'timestamp': tick.timestamp
        }
        self._push_event(market_event)
        
    def generate_signal(self, strategy_id: str, action: str):
        """生成交易信号事件"""
        signal_event = {
            'type': 'SIGNAL',
            'strategy_id': strategy_id,
            'action': action,
            'timestamp': self.current_time
        }
        self._push_event(signal_event)
        
    def _push_event(self, event: Dict):
        """事件入队并保持时间顺序"""
        index = np.searchsorted(
            [e['timestamp'] for e in self.event_queue], 
            event['timestamp']
        )
        self.event_queue.insert(index, event)